/*
 * @Author: hyq
 * @LastEditors: hyq
 * @Description:
 * @Date: 2024-01-11 17:50:18
 */
import Taro from "@tarojs/taro";

import {
  clearStorage,
  switchTab,
  taroModal,
  taroToast,
  navigateTo,
} from "@/utils";

interface ResponseType {
  /** 响应的数据为文本 */
  text;
  /** 响应的数据为 ArrayBuffer */
  arraybuffer;
}

enum EMethod {
  /** HTTP 请求 OPTIONS */
  OPTIONS = "OPTIONS",
  /** HTTP 请求 GET */
  GET = "GET",
  /** HTTP 请求 HEAD */
  HEAD = "HEAD",
  /** HTTP 请求 POST */
  POST = "POST",
  /** HTTP 请求 PUT */
  PUT = "PUT",
  /** HTTP 请求 PATCH */
  PATCH = "PATCH",
  /** HTTP 请求 DELETE */
  DELETE = "DELETE",
  /** HTTP 请求 TRACE */
  TRACE = "TRACE",
  /** HTTP 请求 CONNECT */
  CONNECT = "CONNECT",
}
console.log(process.env.TARO_APP_API);
const host = process.env.TARO_APP_API;
export default function HttpRequest<T>(opts: {
  url: string;
  method: string;
  header?: any;
  data: object;
  hideToast?: boolean;
  clear?: boolean;
  responseType?: keyof ResponseType;
  file?: File;
}): Promise<{
  success: boolean;
  code: number;
  message: string;
  data: T;
  token?: string;
  result?: number;
  mobilePhone?: string;
  openId?: string;
}> {
  const { url, data, header = {}, method, clear = true, responseType } = opts;

  Taro.showLoading({ title: "加载中..." });
  const params = filterNull(data);
  const token = Taro.getStorageSync("token");
  const uri = host + url;

  console.log("HttpRequest", uri);
  if (Object.keys(header).length === 0) {
    header["content-type"] = "application/x-www-form-urlencoded";
  }

  return new Promise((resolve, reject) => {
    Taro.request({
      url: uri,
      data: params,
      header: {
        // token,
        "tenant-id": "",
        // 'content-type': 'application/x-www-form-urlencoded',
        ...header,
      },
      timeout: 3000,
      responseType: responseType,
      method: method as EMethod,
      async success(res) {
        Taro.hideLoading();
        const resData: any = res.data;

        if (resData.code >= 500) {
          await taroToast("网络错误，请稍后再试");
          reject(data);
          return;
        }
        if (resData.code === 0) {
          resolve(resData);
        } else if (resData.code === "") {
          await taroToast("登录信息已过期，请重新登录");
          setTimeout(() => {
            clear && clearStorage();
            resolve(resData);
            clear && navigateTo("/pages/login/login");
          }, 1500);
        } else {
          const message = getErrorMessage(resData.msg);

          if (resData.message?.length > 6) {
            await taroModal({
              showCancel: false,
              title: "提示",
              content: message,
            });
          } else {
            !opts.hideToast && (await taroToast(message || "服务异常"));
          }
          resolve(resData);
        }
      },
      async fail(res) {
        Taro.hideLoading();
        console.log(res);

        setTimeout(async () => {
          await taroToast("连接超时，请检查您的网络");
        });
        reject({
          success: false,
          code: "000",
          message: "连接超时，请检查您的网络",
        });
      },
    });
  });
}

/**
 * 获取错误的信息
 * @param dataMessaqge H
 * @returns
 */
function getErrorMessage(dataMessaqge) {
  if (!dataMessaqge) {
    return "";
  }
  const isHas = dataMessaqge.indexOf("内部错误") > -1 ? true : false;
  const message = isHas ? "网络错误，请稍后再试" : dataMessaqge || "";
  return message;
}

function filterNull(o: any) {
  // 过滤空参数
  for (const key in o) {
    const value: any = o[key];
    if (toType(o[key]) !== "boolean" && value !== 0 && !value) {
      delete o[key];
    }
    if (toType(o[key]) === "string") {
      o[key] = o[key].trim();
      if (o[key].length === 0) {
        delete o[key];
      }
    }
  }
  return o;
}

function toType(obj: any) {
  // 判断元素类型
  const reg = /\s([a-zA-Z]+)/;
  const originType = {}.toString.call(obj).match(reg);
  const type: any = originType && originType[1];
  return type.toLowerCase();
}
